<template>
	<view class="container">
		<view class="form bg-fff p-tb-sms">
			<view class="form-item">
				<view class="flex u-row-between">
					<view class="form-item-label">
						<u-icon name="map-fill" color="#731e1f" size="28"></u-icon>
						<text>当前选择</text>
						<view class="form-item-active">{{vuex_address==''?maplocation.city:vuex_address}}</view>
					</view>
					<view class="refrechLocation" @click="getlocation">重新定位 <u-icon name="reload"></u-icon></view>
				</view>
				
				<view class="form-item-txt">
					<u-search placeholder="搜索城市" :show-action="false" :value="keyword" data-key="keyword" @input="inputChange" clearabled="true"></u-search>
					<view class="searchlist" v-if="searchdata.length>0">
						<view class="search-txt" v-for="(sitem,sindex) in searchdata" :key="sindex" @click="changeme(sitem.province,sitem.city)">{{sitem.city}}</view>
					</view>
				</view>
				
			</view>
			
		</view>
		
		<scroll-view class="scroll-list" :scroll-into-view="scrollViewId" scroll-y="true" scroll-with-animation  :style="{height:winHeight + 'px'}">
			
			<view class="form bg-fff p-tb-sm" v-for="(item,index) in citylist" :key="index" :id="item.letter == '#' ? 'indexed-list-YZ' :'indexed-list-' + item.letter">
				<view class="item-list" v-for="(pitem,pindex) in item.data" :key="pindex">
					<view class="item-title">{{pitem.label}}</view>
					<view class="item-chid-list">
						<view class="item-title-chid" v-for="(citem,cindex) in pitem.children" :key="cindex" @click="changeme(pitem.label,citem.label)">
							<view>{{citem.label}}</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="right-menu">
			<view v-for="(i,index) in Letters" :key="index" @click="jumper(i,index)" :class="jumperIndex == i?'letter-item active':'letter-item'">{{i}}</view>
		</view>
	</view>
</template>

<script>
	import {pinyin} from '../../common/Convert_Pinyin.js';
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				isExpanded:true,
				form: {},
				longitude: 0,
				latitude: 0,
				storeInfo: {},
				warehouseInfo: {},
				mycity:'',
				regionList:[],
				citylist:[],
				Letters:[],
				jumperIndex:0,
				scrollViewId:"indexed-list-YZ",
				keyword:'',
				addressList:[]
			}
		},
		methods: {
			...mapMutations(['setcity','setRegionstate','setRegionLitterstate','setMapAddress','cleanMapAddress'])
		},
		computed:{
			searchdata(){
				let schlist = [];
				if(this.keyword){
					let citylist = this.regionList
					let chidcity = [];
					let outbreak = 0;
					citylist.forEach((item)=>{
						if(outbreak==1){
							return false;
						}
						if(item.children.length>0){
							item.children.forEach((citem)=>{
								if(schlist.length>=10){
									return false;
								}
								if(citem.label.includes(this.keyword)){
									schlist.push({province:item.label,city:citem.label});
									if(schlist.length>=10){
										schlist.push({province:"-",city:"......"});
										outbreak = 1;
										return false;
									}
								}
							})
						}
					})
				}
				return schlist;
			},
			...mapState(['maplocation','regionlist','regletters','vuex_address']),
		},
		onLoad() {
			// this.mycity = this.maplocation.city;
			this.getHttp();
			// this.getAddress()
			// uni.getLocation({
			// 	type: 'wgs84',
			// 	success: function (res) {
			// 		console.log('当前位置的经度：' + res.longitude);
			// 		console.log('当前位置的纬度：' + res.latitude);
			// 	}
			// });
		},
		onUnload() {
			getApp().globalData.warehouseInfo = {};
		},
		onShow() {
			
		},
		methods: {
			toggleExpand() {
			    this.isExpanded = !this.isExpanded;
			  },
			changeAddressInAddressDetailList(item){
				console.log(item,item.region.province,item.region.city)
				this.$store.commit('setcity',{province:item.region.province,city:item.region.city});
				this.$store.commit('setMapAddress',{
					address_id:item.address_id,
					address:item.detail,
					lng: item.location.lng,
					lat: item.location.lat,
				});
				uni.showToast({
					title: '定位已更新',
					duration: 1000
				});
				setTimeout(()=>{
					uni.navigateBack({delta:1})
				}, 300);
			},
			getAddress() {
				uni.$u.api.getAddress().then(res => {
					this.addressList = res.list;
					
				})
			},
			getlocation(){
				let self = this;
				uni.showLoading({
					title:'定位中'
				})
				uni.getLocation({
					// type: 'wgs84',
					type: 'gcj02',
					success: (res) => {
						uni.$u.api.tencentMapLocation(res.latitude, res.longitude).then(res => {
							// console.log("address",res);
							// console.log(res.data.result.address_component.province,res.data.result.address_component.city)
							this.$store.commit('cleanMapAddress');
							self.$store.commit('setcity',{province:res.data.result.address_component.province,city:res.data.result.address_component.city});
							self.$store.commit('setloaded');
							uni.showToast({
								title: '定位已获取',
								duration: 1000
							});
							setTimeout(()=>{
								uni.hideLoading()
								uni.navigateBack({delta:1})
							}, 300);
						})
					},
					fail: () => {
						console.log('fail location')
						uni.hideLoading()
					}
				});
			},
			inputChange(e){
				this.keyword = e;
			},
			jump(url) {
				uni.navigateTo({
					url: url
				})
			},
			async getRegion() {
				let self = this;
				if(self.regionlist.length>0){
					let regionList = self.regionlist;
					self.regionList = regionList;
					self.pySort(regionList);
					console.log("get cache region list",self.citylist)
				}else{
					uni.$u.api.getRegion({
						treelv:1
					}).then(async function(res){
						let regionList = res.regionData;
						self.regionList = regionList;
						self.$store.commit('setRegionstate',regionList);
						self.pySort(regionList);
					})
				}
				
			},
			getHttp() {
				this.getRegion();
			},
			changeme(pro,city){
				// //刷新上一页
				// let pages = getCurrentPages();
				// let prePage = pages[pages.length - 2];
				// console.log(prePage)
				// // #ifndef H5
				// prePage.$vm.Dorefresh();
				// // #endif
				uni.showLoading({
					title: '切换中..',
					mask: false
				});
				this.mycity = city
				// this.$store.commit('cleanMapAddress');
				this.$store.commit('settempcity',{province:pro,city:city});
				// this.$store.commit('resetdgshow');
				// this.$store.commit('setloaded');
				// uni.setStorageSync('advertisement', true);
				setTimeout(()=>{
					uni.hideLoading()
					uni.navigateBack({delta:1})
				}, 300);
			},
			async pySort(arrList){
				var $this = this;
				if(!String.prototype.localeCompare)
					return null;
				var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split('');//ABCDEFGHJKLMNOPQRSTWXYZ
				var zh = "阿八嚓哒妸发旮哈*讥咔垃痳拏噢妑七呥涩它**穵夕丫帀".split('');
				var result = this.citylist;
				var Letters = this.Letters;
				var curr;
				let currok;
				for(let i=0;i<letters.length;i++){
					curr = {letter: letters[i], data:[]}; //字母对象，data数据
					currok = 0;
					arrList.forEach((n)=>{
						let initial = n.label.charAt(0);//截取第一个字符
						let tbcq = 0;//重庆没弄的
						if(initial=='重'){
							tbcq = 1;
						}
						if(initial==letters[i]||initial==letters[i].toLowerCase()){//首字符是英文的
							curr.data.push(n);
						}else if(zh[i]!=='*'&&$this.isChinese(initial)){//判断是否是无汉字,是否是中文
							let chinaName = pinyin.getFullChars(initial).charAt(0); //直接使用pinyin中方法
							if(tbcq==1){
								chinaName = "C";
							}
							if(chinaName==letters[i]||chinaName==letters[i].toLowerCase()){//首字符是英文的
								curr.data.push(n);
								if(Letters.indexOf(letters[i])===-1){
									Letters.push(letters[i]);
								}
								currok = 1;
							}
						}
						if(letters[i]=='#'&&!$this.isChar(initial)&&!$this.isChinese(initial)){
							curr.data.push(n);
							if(Letters.indexOf("#")===-1){
								Letters.push("#");
							}
							currok = 1;
						}
					})
					if(currok==1){
						result.push(curr)
					}
				}
				
				// this.citylist = result; //citylist 是data中定义的 []
				// console.log(this.citylist)
				// console.log(this.Letters)
			},
			isChinese:function(temp){
			    var re=/[^\u4E00-\u9FA5]/;
			    if (re.test(temp)){return false;}
			    return true ;
			},
			isChar:function(char){
			    var reg = /[A-Za-z]/;
			    if (!reg.test(char)){return false ;}
			    return true ;
			},
			jumper(event,i){
				this.jumperIndex = event;
				let len = this.citylist[i].data.length;
				if(event == '#'){
					this.scrollViewId = 'indexed-list-YZ';
					return
				}
				if(len>0){
					console.log(111);
					this.scrollViewId = 'indexed-list-' + event;
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx 30rpx 0 30rpx;
		
		.scroll-list{
			height: calc(100vh - 240rpx);
		}
		.map {
			border-radius: 16rpx;
			padding: 32rpx;
			
			.map-con {
				width: 100%;
				height: 196rpx;
			}
			
			.map-select {
				// margin-top: 20rpx;
			}
		}
		.right-menu{
			width: 40rpx;
			position: fixed;
			right: -8rpx;
			top: calc(50vh);
			transform: translate(-50%,-50%);
			.letter-item{
				font-size: 24rpx;
				font-family: Verdana, Geneva, Tahoma, sans-serif;
				display: block;
				text-align: center;
				background-color: #e8e8e8;
				color: #000;
				line-height: 40rpx;
				border-radius: 20rpx;
				margin-bottom: 5rpx;
				z-index: 10;
				&.active{
					color: #fff;
					background-color: #BB0024;
					font-weight: bold;
				}
			}
		}
		.form {
			padding: 40rpx 32rpx;
			border-radius: 16rpx;
			margin-bottom: 20rpx;
			margin-top: 22rpx;
			
			&.p-tb-sm{
				padding-top: 20rpx;
				padding-bottom: 20rpx;
			}
			&.p-tb-sms{
				margin-top: 0;
				padding-top: 20rpx;
				padding-bottom: 20rpx;
			}
			.item-list{
				display: flex;
				flex-direction: column;
			}
			.item-title{
				font-size: 28rpx;
				font-weight: bold;
				line-height: 40rpx;
			}
			.item-chid-list{
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				padding:20rpx 0;
				.item-title-chid{
					font-size: 26rpx;
					padding:10rpx 20rpx;
					margin-right: 25rpx;
					margin-bottom: 15rpx;
					border-radius: 4px;
					font-weight: 500;
					color: #000;
					background-color: #eee;
					border: 1px solid #eee;
				}
			}
			
			.form-item {
				.form-item-label {
					font-size: 26rpx;
					color: #333333;
					margin-bottom: 10rpx;
					display: flex;
					align-items: center;
					.form-item-active{
						font-size: 28rpx;
						padding:0rpx 20rpx;
						border-radius: 4px;
						font-weight: 500;
						color: #000;
						max-width: 300rpx;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
				.form-item-txt{
					margin-top: 20rpx;
					margin-bottom: 25rpx;
					position: relative;
					.searchlist{
						width: 100%;
						position: absolute;
						top: 70rpx;
						border:1px solid #eee;
						border-radius: 15rpx;
						background: #fff;
						z-index: 11;
						.search-txt{
							padding-left: 30rpx;
							font-size: 28rpx;
							line-height: 70rpx;
							border-bottom: 1px solid #eee;
						}
					}
				}
			}
			
			.form-item +.form-item {
				margin-top: 20rpx;
			}
		}
		.usualLocation{
			width: 100%;
			background-color: #fff;
			// padding-top: 20rpx;
			// padding-bottom: 20rpx;
			padding-left: 32rpx;
			padding-right: 32rpx;
			display: flex;
			flex-direction: column;
			gap: 10px;
			.locationDetail{
				// margin-bottom: 10px;
				overflow: hidden;
				// white-space: nowrap;
				text-overflow: ellipsis;
			}
		}
		.expand-button{
			padding-left: 32rpx;
			padding-right: 32rpx;
			display: flex;
			justify-content: space-between;
			.e_btn{
				color: #2b54e4;
			}
		}
	}
</style>
